package com.liu.websocket.controller;

import com.liu.websocket.socket.WebSocketServer;
import entity.Result;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import status.CodeEnum;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/messageCenter")
public class MessageCenterController {

    //页面请求
    @GetMapping("/socket/{cid}")
    public ModelAndView socket(@PathVariable String cid,ModelAndView mode) {
        System.out.println(cid+"接收的数据为：");
        mode.setViewName("/socket");
        Map map = new HashMap();
        map.put("cid",cid);
        mode.addObject(map);

        return mode;
    }


    @GetMapping("/test/jquery")
    public String testJquery(Model model) {
        Map map = new HashMap();
        map.put("hello","hellowld");
        model.addAllAttributes(map);

        return "/jquery";
    }

    //推送数据接口

    @PostMapping("/socket/push/{cid}")
    @ResponseBody
    public Result pushToWeb(@PathVariable String cid, String message) {
        try {
            WebSocketServer.sendInfo(message,cid);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, CodeEnum.ERROR.getCode(),e.getMessage());
        }
        return new Result(true, CodeEnum.OK.getCode(),"消息推送成功");
    }


    @PostMapping("/socket/test/{num}")
    @ResponseBody
    public Result pushTest(@PathVariable int num, String message) throws IOException {
           for (int i=0;i<num;i++){
               WebSocketServer.sendInfo("heart",null);
           }


        return new Result(true, CodeEnum.OK.getCode(),"消息推送成功");
    }

}
